//
//  WKVerifyPhoneViewController.m
//  WeKeTang
//
//  Created by ichina on 2017/9/5.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKVerifyPhoneViewController.h"
#import "WKNavgationController.h"
#import "WKForgetPasswordController.h"
#import "WKRegistViewController.h"
#import "WKHomeViewController.h"
#import "WKProfireViewController.h"
#import "WKNetworkTools.h"
#import "WKUniversal.h"
#import "WKLoginHandel.h"
@interface WKVerifyPhoneViewController ()

@property (weak, nonatomic) IBOutlet UITextField *TFPhone;
@property (weak, nonatomic) IBOutlet UITextField *TFVerifyCode;

@property (weak, nonatomic) IBOutlet UIButton *btnVerifyCode;
@property (weak, nonatomic) IBOutlet UIButton *BtnComplete;
@property (nonatomic, strong) NSTimer * verifyTimer;
@property (nonatomic, assign) NSInteger verifyCounter;
@property (nonatomic, assign) NSInteger verifyCode;

@end

@implementation WKVerifyPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    _verifyCounter = 60;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.view.backgroundColor = RGBColor(245, 245, 245);
    
    [self setupUI];
    
}
- (void)setupUI{
    
    if (_isBinding) {
        self.navItem.title = @"绑定已有账号";
    }else{
        self.navItem.title = @"验证您的手机号";
    }
    self.btnVerifyCode.layer.cornerRadius = 2;
    self.btnVerifyCode.layer.masksToBounds = YES;
    self.BtnComplete.layer.cornerRadius = 2;
    self.BtnComplete.layer.masksToBounds = YES;
    
    UIView *leftView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView1.contentMode = UIViewContentModeCenter;
    self.TFPhone.leftView = leftView1;
    self.TFPhone.leftViewMode = UITextFieldViewModeAlways;
    self.TFPhone.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFPhone.layer.borderWidth = 1;
    UIView *leftView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView2.contentMode = UIViewContentModeCenter;
    self.TFVerifyCode.leftView = leftView2;
    self.TFVerifyCode.leftViewMode = UITextFieldViewModeAlways;
    self.TFVerifyCode.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFVerifyCode.layer.borderWidth = 1;
    
    self.TFPhone.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.TFVerifyCode.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.navgationBar.hidden = NO;
    [self.navgationBar setBarTintColor:[UIColor whiteColor]];
    self.statusbar.backgroundColor = [UIColor whiteColor];
}
- (void)backAction{
    [MobClick profileSignInWithPUID:@"binding_for_back"];
    [super backAction];
}
#pragma mark - 获取验证码
- (IBAction)btnVerifyCodeAction:(UIButton *)sender {
    
    if (self.verifyCounter<60) {
        [self showCustomAlertMessage:@"一分钟内不能重复获取验证码"];
        return;
    }
    long verifyCode = [self getRandomNumber:1000 to:9999];
    NSString *callBackStr = [WKUniversal validateMobile:self.TFPhone.text];
    if (callBackStr) {
        [self showCustomAlertMessage:callBackStr];
        return;
    }
    [self startTimer];
    
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"smsnew" forKey:@"commandid"];
    [para setObject:self.TFPhone.text forKey:@"mobile"];
    [para setObject:_S(@"%.0ld",verifyCode) forKey:@"content"];
    [para setObject:@"2" forKey:@"type"];
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"获取中..." completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        [weakSelf showCustomAlertMessage:@"网络错误"];
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dic  = dict[@"head"];
        NSString *statuscode = dic[@"statuscode"];
//        [weakSelf showCustomAlertMessage:@"验证码已发送"];
        NSLog(@"获取验证码：%@",statuscode);
        if ([statuscode  isEqualToString:@"100"]) {
            weakSelf.verifyCode = verifyCode;
        }
    }];
    if (_isBinding) {
        self.verifyCode = verifyCode;
    }
    NSLog(@"验证码是：%ld",self.verifyCode);
}
#pragma mark - 验证手机号
- (IBAction)btnCompleteAction:(UIButton *)sender {
    
    NSString * callBackStr = [WKUniversal validateMobile:self.TFPhone.text];
    if (callBackStr) {
        [self showCustomAlertMessage:callBackStr];
        return;
    }
    if (isExistString(self.TFVerifyCode.text)) {
        [self showCustomAlertMessage:@"验证码不能为空"];
        return;
    }
    
    if (![_S(@"%.0ld",self.verifyCode) isEqualToString:self.TFVerifyCode.text] ) {
        [self showCustomAlertMessage:@"您输入的验证码有误，请从新输入!"];
        return;
    }
    __weak typeof(self) weakSelf = self;
    if (_isBinding) {
        [MobClick profileSignInWithPUID:@"binding_for_binding"];
        //微信或qq绑定手机号接口
        NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
        NSMutableDictionary *para = [NSMutableDictionary dictionary];
        [para setObject:@"openrelate" forKey:@"commandid"];
        [para setObject:self.TFPhone.text forKey:@"mobile"];
        [para setObject:self.site forKey:@"site"];
        [para setObject:self.openid forKey:@"openid"];
        [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
        [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"绑定中" completionHandler:^(id responseObject) {
            
        } errorHandler:^(NSError *error) {
            
        } finishHandler:^(id responseObject) {
            NSDictionary *dict = [responseObject mj_JSONObject];
            NSDictionary *dic  = dict[@"head"];
            NSString *statuscode = dic[@"statuscode"];
            NSString *message = dic[@"message"];
            NSLog(@"---------%@",dict);
            if ([statuscode intValue] == 100) {
                [self showCustomAlertMessage:@"绑定成功"];
                //绑定成功
                //登录成功
                WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
                mainVC.userId = userid;
                WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
                
            }else if ([statuscode intValue] == 999){
                [self showCustomAlertMessage:message];
                //绑定未成功 跳到注册页面
                WKRegistViewController *registerVC = [[WKRegistViewController alloc]init];
                registerVC.isBinding = YES;
                registerVC.site = self.site;
                registerVC.openid = self.openid;
                [self.navigationController pushViewController:registerVC animated:YES];
            }
            
        }];
        
        
    }else{
        //正常验证手机号接口
        NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
        NSMutableDictionary *para = [NSMutableDictionary dictionary];
        [para setObject:@"verifyphone" forKey:@"commandid"];
        [para setObject:self.TFPhone.text forKey:@"phone"];
        [para setObject:userid forKey:@"uid"];
        [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
        [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain completionHandler:^(id responseObject) {
            
        } errorHandler:^(NSError *error) {
            [weakSelf showCustomAlertMessage:@"网络错误"];
            
        } finishHandler:^(id responseObject) {
            NSDictionary *dict = [responseObject mj_JSONObject];
            NSDictionary *dic  = dict[@"head"];
            NSString *statuscode = dic[@"statuscode"];
//            NSLog(@"获取验证码%@",statuscode);
            if ([statuscode  isEqualToString:@"100"]) {
                 [weakSelf showCustomAlertMessage:@"验证成功"];
                //验证成功
                WKForgetPasswordController *forgetVC = [[WKForgetPasswordController alloc]init];
                [self.navigationController pushViewController:forgetVC animated:YES];
            }
        }];
        
    }
}
#pragma mark - 开启定时器
- (void)startTimer{
    [MobClick profileSignInWithPUID:@"binding_for_getcode"];
    self.verifyCounter = 60;
    __weak typeof(self) weakSelf = self;
    if (self.verifyTimer && [self.verifyTimer isValid]) {
        [self.verifyTimer invalidate];
    }
    self.verifyTimer = [NSTimer scheduledTimerWithTimeInterval:1 block:^(NSTimer * _Nonnull timer) {
        weakSelf.verifyCounter--;
        if (weakSelf.verifyCounter<=0) {
            [weakSelf stopTimer];
        }
        else{
            [weakSelf.btnVerifyCode setTitle:_S(@"%ld秒后重试",weakSelf.verifyCounter) forState:UIControlStateNormal];
        }
    } repeats:YES];
}
- (void)stopTimer{
    if (self.verifyTimer && [self.verifyTimer isValid]) {
        [self.verifyTimer invalidate];
        self.verifyTimer = nil;
    }
    self.verifyCounter = 60;
    [self.btnVerifyCode setTitle:@"获取验证码" forState:UIControlStateNormal];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
}
- (long)getRandomNumber:(long)from to:(long)to{
    return (long)(from + (arc4random() % (to - from + 1)));
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
